//
//  WebViewController.m
//  Onskysell
//
//  Created by 陈刚 on 17/6/5.
//  Copyright © 2017年 cg. All rights reserved.
//

#import "WebViewController.h"
#import "ShareHelp.h"
#import "NetFailView.h"
#import "LJWebKitSupport.h"
#import <WebKit/WebKit.h>
#import "NetworkLostHUD.h"
#import "topBarView.h"

@interface WebViewController ()<WKNavigationDelegate>

//@property (nonatomic, strong) LYBaseWKWebView *wkWeb;

@property (nonatomic, strong) NetFailView *netFailView;

@property (nonatomic, strong) topBarView *topBarView;

@property (nonatomic, strong) NSTimer *requestTimer;

@property (nonatomic, assign) BOOL webLoadFinished;

@property (nonatomic, strong) UIView *topView;

@property (nonatomic, copy) NSString *currentJs;

@property (nonatomic, copy) NSString *currentLoadUrl;

//@property (nonatomic, strong) UIProgressView *progressView;
@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupView];
    
    [self addConstraint];
    
    [self loadData];
    
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //    [self loadData];
    [NotificationCenter addObserver:self selector:@selector(refreshNet:) name:RefreshNetNotification object:nil];
    [NotificationCenter addObserver:self selector:@selector(jsEvent:) name:JSKNotification object:nil];
    [NotificationCenter addObserver:self selector:@selector(changeColor:) name:CHANGECOLORKNotification object:nil];
    [NotificationCenter addObserver:self selector:@selector(changeWordColor:) name:CHANGEWORDCOLORNoti object:nil];
    //现在不要截屏分享了~!
//    [NotificationCenter addObserver:self selector:@selector(userDidTakeScreenshot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    [NotificationCenter addObserver:self selector:@selector(netFailBackHome:) name:NetFailBackHomeNoti object:nil];
    [NotificationCenter addObserver:self selector:@selector(topBarBackClick) name:TopBarBack object:nil];
    
    [NotificationCenter addObserver:self selector:@selector(applicationDidEnterForeground) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    [NotificationCenter addObserver:self selector:@selector(applicationDidEnterForeground) name:Foreground_Push_Get object:nil];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.isNotFirstLoad = NO;
    [NotificationCenter removeObserver:self name:RefreshNetNotification object:nil];
    [NotificationCenter removeObserver:self name:JSKNotification object:nil];
    [NotificationCenter removeObserver:self name:CHANGECOLORKNotification object:nil];
    [NotificationCenter removeObserver:self name:CHANGEWORDCOLORNoti object:nil];
    //现在不要截屏分享了~!
//    [NotificationCenter removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    [NotificationCenter removeObserver:self name:NetFailBackHomeNoti object:nil];
    [NotificationCenter removeObserver:self name:TopBarBack object:nil];
    [NotificationCenter removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [NotificationCenter removeObserver:self name:Foreground_Push_Get object:nil];
}

- (void)applicationDidEnterForeground
{
    NSDictionary *ext = [[NSUserDefaults standardUserDefaults] objectForKey:@"UMPushInfoDic"];
    if (ext) {
        [self handleWithPushNotiExt:ext];
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"UMPushInfoDic"];
    }
}

- (void)dealloc
{
//    [self.wkWeb removeObserver:self forKeyPath:@"URL"];
//    [self.wkWeb removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)setupView{
    
    [self setStatusBarBackgroundColor:StatusBarColor];//默认
    
    self.topView = [[UIView alloc] init];
    [self.topView setBackgroundColor:StatusBarColor];
    [self.view addSubview:self.topView];
    
    self.wkWeb = [[LYBaseWKWebView alloc] initWithFrame:CGRectZero configuration:[LJWebKitSupport sharedSupport].webViewConfiguration];
    //    self.wkWeb.scrollView.backgroundColor = [UIColor whiteColor];
    WS(wkSelf);
    self.wkWeb.navigationDelegate = wkSelf;
    self.wkWeb.scrollView.showsVerticalScrollIndicator = NO;
    self.wkWeb.scrollView.showsHorizontalScrollIndicator = NO;
    self.wkWeb.scrollView.scrollEnabled = NO;
//    self.wkWeb.allowsBackForwardNavigationGestures = YES;
//    [self.wkWeb addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:nil];//防内存过大白屏处理
//    [self.wkWeb addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.view addSubview:self.wkWeb];
    
    [self.navigationController setNavigationBarHidden:YES];
    
    self.webLoadFinished = NO;
    
    [[CGLodingView shareInstance] startAnimation];//第一次进来在启动页后面loading
}

- (void)addConstraint{
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(0));
        make.right.equalTo(@(0));
        make.top.equalTo(@(0));
        make.height.equalTo(@(StatusBarHeight));
    }];
    
    [self.wkWeb mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(0));
        make.right.equalTo(@(0));
        make.top.equalTo(@(StatusBarHeight));
        make.bottom.equalTo(@(0));
    }];
}

- (void)loadData{
    NSDictionary *ext = [[NSUserDefaults standardUserDefaults] objectForKey:@"UMPushInfoDic"];
    if (ext) {
        [self handleWithPushNotiExt:ext];
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"UMPushInfoDic"];
    }
    else {
        [self.wkWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.UrlString]]];
//    [self addCookies];
    }
}

- (void)handleWithPushNotiExt:(NSDictionary *)ext
{
    NSNumber *type = [ext objectForKey:@"type"];
    NSString *url = [ext objectForKey:@"url"];
    if (type) {
        if ([type isKindOfClass:NSNumber.class]) {
            if (type.integerValue == 1) {//跳转链接
                if (url) {
                    if ([LJUtility theString:url containSting:BaseHost]) {
                        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
                        [self.wkWeb loadRequest:request];
                    }
                    else {
                        
                    }
                }
            }
        }
    }
}

- (void)topBarBackClick
{
    if ([self.wkWeb canGoBack]) {
        [self loadJsWithJs:@"javascript:history.back(-1)"];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//cookie 0002 +
//注入上级webview的cookie
//- (void)addCookies
//{
//    NSURL *url = [NSURL URLWithString:self.UrlString];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
//    NSString *cookiesJson = [LJWebKitSupport getCookieJsonWithCookiesArr:cookies];
//    
//    //方法一
////    if (cookiesJson) {
////        // 注入Cookie
////        [request setValue:cookiesJson forHTTPHeaderField:@"Cookie"];
////    }
//    
//    //方法二
//    if (self.cookieStr) {
//        [request setValue:self.cookieStr forHTTPHeaderField:@"Cookie"];
//    }
//    
//    // 加载请求
//    [self.wkWeb loadRequest:request];
//}

#pragma mark ======= observer
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.wkWeb && [keyPath isEqualToString:@"URL"])
    {
        NSURL *newUrl = [change objectForKey:NSKeyValueChangeNewKey];
        NSURL *oldUrl = [change objectForKey:NSKeyValueChangeOldKey];
        if (IsNull(newUrl) && !IsNull(oldUrl)) {
            //            processDidTerminated = YES;
            [self.wkWeb reload];
        };
    }
}

#pragma mark ======= WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    NSString *url = webView.URL.absoluteString;
    NSLog(@"网页开始加载");
    [OKWebViewURLFilter shared].startTimeMsecs = [[NSDate date] timeIntervalSince1970]*1000;
    if (self.requestTimer) {
        [self stopTimer];
    }
    self.webLoadFinished = NO;
    self.requestTimer = [NSTimer scheduledTimerWithTimeInterval:RequestTimeout target:self selector:@selector(requestTimeOut:) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:self.requestTimer forMode:NSRunLoopCommonModes];

    if (self.isNotFirstLoad) {
        if ([[OKWebViewURLFilter shared] filterLoadingUrl:url]) {
            [[CGLodingView shareInstance] startAnimation];
        }
    }
    else self.isNotFirstLoad = YES;
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSLog(@"网页加载完成");
    self.webLoadFinished = YES;
    [[CGLodingView shareInstance] stopAnimation];
    if (DebugMode) [[OKWebViewURLFilter shared] showLoadTimeDif];
    [self stopTimer];
    
    if (!webView.isLoading) {
        
    }
    
    NSString *url = webView.URL.absoluteString;
    if (url) {
        if ([url containsString:BaseWebUrl] || [url containsString:@"http://ios_jsapi"]) {
            [self dismissTobBarView];
        }
        else {//外域
            [self showTobBarView];
        }
    }
    [self handleUrlWithWebResponse];
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    self.webLoadFinished = YES;
    [self handleNetFailWeb];
}

// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    /* cookie 0002 +
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
    //方法一 获取cookie
    NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
    //方法二 读取Set-Cookie字段
    NSString *cookieStr = [[response allHeaderFields] valueForKey:@"Set-Cookie"];
     */
    decisionHandler(WKNavigationResponsePolicyAllow);
}

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSString *url = [navigationAction.request.URL absoluteString];
    
    //UIWebView打开一个页面之后，点击里面的内容就直接能跳转。而WKWebView一开始点里面的东西没反应，只要加了这个方法就好了
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    
//    NSString *BaseHost =
    
    if (([LJUtility theString:url containSting:[NSString stringWithFormat:@"%@/Bid/Detail",BaseHost]] || [LJUtility theString:url containSting:[NSString stringWithFormat:@"%@/Bid/MyBidDetail",BaseHost]]) && self.isNotFirstLoad) {//新开web //isNotFirstLoad防止首次反复加载
        
        WebViewController *web = [[WebViewController alloc] init];
        web.lastWeb = self.wkWeb;
        web.homeWeb = self.homeWeb;
        web.UrlString = url;
        [self.navigationController pushViewController:web animated:YES];
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    else {
        if ([[OKWebViewURLFilter shared] filter:navigationAction.request WebView:webView viewController:self]) {
            if ([LJUtility theString:url containSting:@"ios_jsapi"]) {
                decisionHandler(WKNavigationActionPolicyCancel);
            }
            else {
                self.currentLoadUrl = url;
                [[NSNotificationCenter defaultCenter] postNotificationName:CHANGECOLORKNotification object:@"#ffffff"];
                [[NSNotificationCenter defaultCenter] postNotificationName:CHANGEWORDCOLORNoti object:@"#000000"];
                decisionHandler(WKNavigationActionPolicyAllow);
            }
        }
        else {
            decisionHandler(WKNavigationActionPolicyCancel);
        }
    }
}

- (void)showTobBarView
{
    if (self.topBarView) {
        return;
    }
    
    self.topBarView = [[NSBundle mainBundle] loadNibNamed:@"topBarView" owner:nil options:nil].firstObject;
    self.topBarView.frame = CGRectMake(0, StatusBarHeight, CGRectGetWidth(self.view.frame), 44);
    [self.view addSubview:self.topBarView];
    [self.view bringSubviewToFront:self.topBarView];
    
    [self.wkWeb mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(0));
        make.right.equalTo(@(0));
        make.top.equalTo(@(StatusBarHeight+44));
        make.bottom.equalTo(@(0));
    }];
}

- (void)dismissTobBarView
{
    if (self.topBarView) {
        [self.topBarView removeFromSuperview];
        self.topBarView = nil;
        [self.wkWeb mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(0));
            make.right.equalTo(@(0));
            make.top.equalTo(@(StatusBarHeight));
            make.bottom.equalTo(@(0));
        }];
    }
}

#pragma mark - =========== Other

- (void)jsEvent:(NSNotification *)notif{
    NSString *notiString = [notif object];
    self.currentJs = notiString;
//    [self.webview stringByEvaluatingJavaScriptFromString:notiString];
    if (![_currentJs isEqualToString:@"paypalBackTo"]) {//非从paypal返回订单页
        [self loadJsWithJs:notiString];
    }
}

- (void)loadJsWithJs:(NSString *)js
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.wkWeb evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            [[CGLodingView shareInstance] stopAnimation];
            if (error) {
                NSLog(@"wkWeb evaluateJavaScript error = %@\n", error);
            }
            _currentJs = nil;
        }];
    });
}

- (void)requestTimeOut:(NSTimer *)timer{
//    if (self.webLoadFinished == NO) {
//        [self toErrorWeb];
//        [self stopTimer];
        [self handleNetFailWeb];
//    }
    
}

- (void)handleNetFailWeb
{
    [[CGLodingView shareInstance] stopAnimation];
    [self stopTimer];
    if (self.netFailView) {
        return;
    }

    [self toErrorWeb];
}


- (void)stopTimer{
    [self.requestTimer invalidate];
    self.requestTimer = nil;
}

- (void)changeColor:(NSNotification *)notif{
    NSString *notiString = [notif object];
    [self.topView setBackgroundColor:[UIColor colorWithHexString:notiString]];
    [self setStatusBarBackgroundColor:[UIColor colorWithHexString:notiString]];
}

- (void)changeWordColor:(NSNotification *)notif{
    NSString *notiString = [notif object];
    if ([notiString isEqualToString:@"black"] || [notiString isEqualToString:@"#000000"]) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    }
    else if ([notiString isEqualToString:@"white"] || [notiString isEqualToString:@"#ffffff"]) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
}

- (void)toErrorWeb{
    self.netFailView = [[NSBundle mainBundle] loadNibNamed:@"NetFailView" owner:nil options:nil].firstObject;
    self.netFailView.frame = CGRectMake(0, StatusBarHeight, CGRectGetWidth(self.wkWeb.frame),CGRectGetHeight(self.wkWeb.frame));
    if (![CGNetManage isReachable]) {
        [self.netFailView setNoNetNotice];
    }
    [self.view addSubview:self.netFailView];
}

//设置状态栏颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

- (void)refreshNet:(NSNotification *)notification
{
    if (![CGNetManage isReachable]) {
        [self.netFailView setNoNetNotice];
        [self stopTimer];
        return;
    }
    
//    //清空web
//    [self.wkWeb evaluateJavaScript:@"document.body.innerHTML='';" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//        if (error) {
//            NSLog(@"wkWeb evaluateJavaScript error = %@\n", error);
//        }
//    }];
    
    [self.netFailView removeFromSuperview];
    self.netFailView = nil;
    [self.wkWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.currentLoadUrl]]];
}

- (void)netFailBackHome:(NSNotification *)notification
{
    [self.netFailView removeFromSuperview];
    self.netFailView = nil;
    
    [self.navigationController popToRootViewControllerAnimated:NO];
}

- (void)userDidTakeScreenshot:(NSNotification *)notification
{
    NSLog(@"检测到截屏");
    UIImage *img = [LJUtility getScreenshotImg];
    
    __block NSString *imgPath;
    [CGNetManage httpPostImg:img compress:0.5 success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if ([[[dic objectForKey:@"state"] objectForKey:@"code"] intValue] == 200) {
            NSArray *pathArr = [dic objectForKey:@"data"];
            if (pathArr.count>0) {
                if (imgPath == nil) {
                    imgPath = pathArr.firstObject;
                    [[NSUserDefaults standardUserDefaults] setObject:imgPath forKey:@"screenshotUrl"];
                    [[ShareHelp shared] shareWithTitle:ScreenShotTitle content:nil image:img url:BaseWebUrl currentController:self fromType:FromScreenshot];
                }
            }
        }
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"截屏图片上传失败~");
    }];
    
//    [[ShareHelp shared] shareWithTitle:ScreenShotTitle content:nil image:img url:BaseWebUrl currentController:self fromType:FromScreenshot];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)handleUrlWithWebResponse
{
    if ([self isNeedHideWebNavBar]) {
        [self hideWebNavBarJS];
    }
}

//是否隐藏web顶部导航栏
- (BOOL)isNeedHideWebNavBar
{
    if ([self.UrlString isEqualToString:CarList_Url_1] || [self.UrlString isEqualToString:CarList_Url_2]) {
        self.topBarView.titleLbl.text = @"购物车";
        return YES;
    }
    
    return NO;
}

- (void)hideWebNavBarJS
{
    NSString *js = @"$(\".ft-header\").hide();$(\".ft-overflow\").offset({top:0});$(\"#btnLogout\").click(function(){});";//@"document.getElementsByClassName(\"ft-header\").css(\"display\", \"none\");";//@"document.getElementsByClassName('ft-header').style.display=\"none\"";//@"$(\".ft-header\").hide();";
    [self loadJsWithJs:js];
}
@end
